from django import forms
from django_redis import get_redis_connection
from django.core.validators import RegexValidator, ValidationError

from utils.encrypt import md5


class LoginForm(forms.Form):
    role = forms.ChoiceField(
        label='角色',
        required=True,  # 校验的字段required=True字段不允许空
        widget=forms.Select(
            attrs={'class': 'form-control', 'name': 'role'}),
        choices=[(1, '管理员'), (2, '用户')])
    username = forms.CharField(
        label='用户名',
        required=True,
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'name': 'username', 'placeholder': '用户名'}),
        max_length=32,
        min_length=2,
        error_messages={'max_length': '用户名最长为32位', 'min_length': '用户名最少为2位', 'required': '用户名不能为空'}
    )
    password = forms.CharField(
        label='密码',
        required=True,
        widget=forms.PasswordInput(
            attrs={'class': 'form-control', 'name': 'password', 'placeholder': '密码'}),
        max_length=32,
        min_length=4,
        error_messages={'max_length': '密码最长为32位', 'min_length': '密码最少为4位', 'required': '密码不能为空'})

    def clean_username(self):
        username = self.cleaned_data.get('username')
        # from django.core.exceptions import ValidationError
        # if len(username) < 5:
        #     raise ValidationError('用户名长度不能小于5位')
        return username

    def clean_password(self):
        password = self.cleaned_data.get('password')
        password = md5(password)
        return password


class SmsLoginForm(forms.Form):
    role = forms.ChoiceField(
        label='角色',
        required=True,  # 校验的字段required=True字段不允许空
        widget=forms.Select(
            attrs={'class': 'form-control', 'name': 'role'}),
        choices=[(1, '管理员'), (2, '用户')])
    mobile = forms.CharField(
        label='手机号',
        required=True,
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'name': 'mobile', 'placeholder': '手机号'}),
        max_length=11,
        validators=[RegexValidator(r'^\d{11}$', '请输入正确的手机号')],
        min_length=11,
        error_messages={'max_length': '手机号最长为11位', 'min_length': '手机号最少为11位',
                        'required': '手机号不能为空'}
    )
    code = forms.CharField(
        label='验证码',
        required=True,
        widget=forms.PasswordInput(
            attrs={'class': 'form-control', 'name': 'code', 'placeholder': '验证码'}),
        max_length=4,
        min_length=4,
        validators=[RegexValidator(r'^[0-9]{4}$', '请输入4位数字')],
        error_messages={'max_length': '验证码最长为4位', 'min_length': '验证码最少为4位', 'required': '验证码不能为空'})

    def clean_mobile(self):
        # role = self.cleaned_data.get('role')
        mobile = self.cleaned_data.get('mobile')
        #
        # if role == '1':
        #     user_project = models.Administrator.objects.filter(active=1, mobile=mobile).first()
        # else:
        #     user_project = models.Customer.objects.filter(active=1, mobile=mobile).first()
        #
        # if not user_project:
        #     raise ValidationError('手机号不存在')
        return mobile

    def clean_code(self):
        mobile = self.cleaned_data.get('mobile')
        code = self.cleaned_data.get('code')
        if not mobile:
            return code

        conn = get_redis_connection()
        cache_code = conn.get(mobile)  # 字节类型需转换为字符串
        if not cache_code:
            raise ValidationError('验证码已过期')

        if code != cache_code.decode('utf-8'):
            raise ValidationError('验证码不正确')

        return code


class MobileForm(forms.Form):
    role = forms.ChoiceField(
        label='角色',
        required=True,  # 校验的字段required=True字段不允许空
        widget=forms.Select(
            attrs={'class': 'form-control', 'name': 'role'}),
        choices=[(1, '管理员'), (2, '用户')])

    mobile = forms.CharField(
        label='手机号',
        validators=[RegexValidator(r'^\d{11}$', '请输入正确的手机号')],
        widget=forms.TextInput(
            attrs={'class': 'form-control', 'name': 'mobile', 'placeholder': '手机号'}),
        max_length=11,
        min_length=11,
        error_messages={'max_length': '手机号最长为11位', 'min_length': '手机号最少为11位',
                        'required': '手机号不能为空'}
    )
